<script setup>
import request from "@/utils/request";
import { ref } from 'vue';
import { useRouter } from 'vue-router';

const router = useRouter();
const form = ref({});
const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' }
  ],
  confirm: [
    { required: true, message: '请确认密码', trigger: 'blur' }
  ]
};

const register = () => {
  if (form.value.password !== form.value.confirm) {
    // 假设 $message 是通过 app.config.globalProperties.$message 挂载的全局方法
    app.config.globalProperties.$message({
      type: "error",
      message: '2次密码输入不一致！'
    });
    return;
  }
  // 模拟 $refs['form'].validate 的行为
  const validate = () => {
    const fields = Object.keys(rules);
    for (const field of fields) {
      const fieldRules = rules[field];
      for (const rule of fieldRules) {
        if (rule.required && !form.value[field]) {
          app.config.globalProperties.$message({
            type: "error",
            message: rule.message
          });
          return false;
        }
      }
    }
    return true;
  };
  if (validate()) {
    request.post("/user/register", form.value).then(res => {
      if (res.code === '0') {
        app.config.globalProperties.$message({
          type: "success",
          message: "注册成功"
        });
        router.push("/login");
      } else {
        app.config.globalProperties.$message({
          type: "error",
          message: res.msg
        });
      }
    });
  }
};
</script>

<template>
  <div style="width: 100%; height: 100vh; overflow: hidden">
    <div style="width: 400px; margin: 100px auto">
      <div style="font-size: 30px; text-align: center; padding: 30px 0">欢迎注册</div>
      <el-form ref="form" :model="form" size="normal" :rules="rules">
        <el-form-item label="用户名" prop="username">
          <el-input prefix-icon="el-icon-user-solid" v-model="form.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input prefix-icon="el-icon-lock" v-model="form.password" show-password></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="confirm">
          <el-input prefix-icon="el-icon-lock" v-model="form.confirm" show-password></el-input>
        </el-form-item>
        <el-form-item>
          <el-button style="width: 100%" type="primary" @click="register">注册</el-button>
        </el-form-item>
        <el-form-item><el-button type="text" @click="$router.push('/login')">&lt;&lt;返回登录 </el-button></el-form-item>
      </el-form>
    </div>
  </div>
</template>

<style scoped></style>
